import React, { useState, useCallback, useEffect } from "react";
import { NextPage } from "next";
import { PageHeader, Input, Button, message } from "antd";

import { Editor as BEditor } from "@/components/Editor";
import style from "./index.module.scss";
import { FileDrawer } from "@/components/FileDrawer";
import { ArticleApi } from "@/api/article";
import { ArticleSetting } from "@/components/ArticleSetting";
const STATUS = {
  DRAFT: "draft",
  PUBLISH: "publish",
};
interface IProps {
  id: any;
}
const Editor: NextPage<IProps> = ({ id }) => {
  const [visible, setVisible] = useState(false);
  // 发布文章设置面板
  const [settingVisible, setSettingVisible] = useState(false);
  // 设置文章
  const [article, setArticle] = useState<any>({});
  // 设置文章标题
  const [title, setTitle] = useState("");

  // 初始化文章数据
  useEffect(() => {
    ArticleApi.getArticle(id).then((res) => {
      setArticle(res);
      setTitle(res.title);
    });
  }, [id]);

  // 更新文章
  const save = useCallback(() => {
    if (!article.title) {
      message.warn("请输入文章标题");
      return;
    }
    // 需要传递的标签格式是字符串
    if (Array.isArray(article.tags)) {
      article.tags = article.tags.map((t) => t.id).join(",");
    }
    // 需要传递的分类是一个id
    if (article.category && article.category.id) {
      article.category = article.category.id;
    }
    ArticleApi.updateArticle(id, article).then((res) => {
      message.success(
        article.status === STATUS.DRAFT ? "文章已保存为草稿" : "文章已发布"
      );
    });
  }, [article, title]);
  // 预览
  const preview = () => {};
  // 发布
  const publish = () => {
    let canPublish = true;
    void [
      ["title", "请输入标题"],
      ["content", "请输入文章内容"],
    ].forEach(([key, msg]) => {
      if (!article[key]) {
        message.warn(msg);
        canPublish = false;
      }
    });
    if (!canPublish) {
      return;
    }
    setSettingVisible(true);
  };
  //保存并发布
  const saveOrPublish = (patch) => {
    const data = Object.assign({}, article, patch);
    // 存在id表示时编辑文章
    if (data.category && data.category.id) {
      data.category = data.category.id;
    }
    if (Array.isArray(data.tags)) {
      data.tags = data.tags.map((t) => t).join(",");
    }
    data.title = title;
    const handle = () => {
      message.success(
        data.status === STATUS.DRAFT ? "文章已保存" : "文章已发布"
      );
      setSettingVisible(false);
    };
    if (id) {
      ArticleApi.updateArticle(id, data).then(handle);
    } else {
      ArticleApi.addArticle(data).then(handle);
    }
  };
  return (
    <div className={style.wrapper}>
      <PageHeader
        onBack={() => window.close()}
        title={
          <Input
            placeholder="文章标题"
            value={title}
            onChange={(e) => {
              article.title = e.target.value;
              setArticle(article);
              setTitle(e.target.value);
            }}
          />
        }
        extra={[
          <Button
            type="dashed"
            key={3}
            onClick={() => {
              setVisible(true);
            }}
          >
            文件库
          </Button>,
          <Button key={1}>预览</Button>,
          <Button key={2} onClick={save}>
            更新
          </Button>,
          <Button key={4} onClick={publish} type="primary">
            发布
          </Button>,
        ]}
      ></PageHeader>
      <div className={style.container}>
        <BEditor
          value={article.content}
          onChange={(value) => {
            article.content = value;
            setArticle(article);
            return article;
          }}
        />
      </div>
      <FileDrawer
        visible={visible}
        isCopy={true}
        closeAfterClick={false}
        onClose={() => {
          setVisible(false);
        }}
      />
      <ArticleSetting
        onChange={saveOrPublish}
        article={article}
        visible={settingVisible}
        onClose={() => setSettingVisible(false)}
      />
    </div>
  );
};

Editor.getInitialProps = (ctx) => {
  const { id } = ctx.query;
  return { id };
};

export default Editor;
